package commonwebgroup.commonwebartifact.Helper;

import org.bukkit.plugin.java.JavaPlugin;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

public class HttpHelper {

    private  JavaPlugin   _plugin ;
    private String apiKey;
    public HttpHelper (JavaPlugin  plugin){

        _plugin = Objects.requireNonNull(plugin,"java plugin  not allow null");
        apiKey = _plugin.getConfig().getString("api-key");
    }

    public String escapedStrHandle(String response){
        response = response.replace("\\", "");
        // 去掉开头的引号
        if (response.startsWith("\"")) {
            response = response.substring(1);
        }

        // 去掉结尾的引号
        if (response.endsWith("\"")) {
            response = response.substring(0, response.length() - 1);
        }

        return response;
    }

    public CompletableFuture<String> sendPostRequest(String urlString, String jsonInputString) {
        HttpClient httpClient = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
                .connectTimeout(Duration.ofSeconds(10))
                .build();

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(urlString))
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .header("ApiKey", apiKey)
                .POST(HttpRequest.BodyPublishers.ofString(jsonInputString, StandardCharsets.UTF_8))
                .build();

        return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .exceptionally(e -> {
                    e.printStackTrace();
                    return null;
                });

    }
}
